import React, { useEffect, useState, useRef, useMemo } from 'react'
import { Input, Avatar, message } from 'antd'
import { UserOutlined } from '@ant-design/icons'
import localforage from 'localforage'
import styles from './index.module.less'
import PubSub from 'pubsub-js'
const { TextArea } = Input
import { getGlobalState } from '@/utils/qiankunActions'
import { getFriendInfoApi } from '@/request/api/friend'
import { sseSendChattingMessageApi } from '@/request/api/chatHistory'
import { sourceUrl } from '@/config/baseConfig'

//
//
export default function ChattingBox({
  chatRecordList = [],
  chatUserId,
}: {
  chatRecordList: chatRecordItf[]
  chatUserId: string
}) {
  const dividerRef = useRef(null)
  const chatMessagesRef = useRef(null)
  const messageEditorRef = useRef(null)

  // 调节聊天记录框和消息编辑器的高度
  useEffect(() => {
    let isDragging = false
    let dividerStartPosition = 0
    let chatMessagesStartHeight = 0

    const handleMouseDown = (event) => {
      isDragging = true
      dividerStartPosition = event.clientY
      chatMessagesStartHeight = chatMessagesRef.current.offsetHeight
    }

    const handleMouseMove = (event) => {
      if (!isDragging) return

      const deltaY = event.clientY - dividerStartPosition
      const newChatMessagesHeight = chatMessagesStartHeight + deltaY

      chatMessagesRef.current.style.height = `${newChatMessagesHeight}px`
      messageEditorRef.current.style.height = `calc(100% - ${newChatMessagesHeight}px - 5px)`
    }

    const handleMouseUp = () => (isDragging = false)

    const d = dividerRef.current
    const c = chatMessagesRef.current
    const m = messageEditorRef.current
    if (!d || !c || !m) return

    const element = dividerRef.current
    element.addEventListener('mousedown', handleMouseDown)
    document.addEventListener('mousemove', handleMouseMove)
    document.addEventListener('mouseup', handleMouseUp)

    return () => {
      element.removeEventListener('mousedown', handleMouseDown)
      document.removeEventListener('mousemove', handleMouseMove)
      document.removeEventListener('mouseup', handleMouseUp)
    }
  }, [])

  //
  //
  useEffect(() => {
    if (chatUserId) getFriendInfo(chatUserId)
  }, [chatUserId])

  const [userInfo, setUserInfo] = useState<getFriendInfoItf>(null)

  // 获取用户的最新信息，并将信息保存到浏览器缓存中
  const getFriendInfo = async (id: string) => {
    const res = await getFriendInfoApi(id)
    if (res.code !== 200) return message.error('获取用户信息错误！')
    setUserInfo(res.data)

    setTimeout(async () => {
      const { account } = getGlobalState().userInfo
      const data: { [key: string]: localChatUsersItf } =
        await localforage.getItem(`${account}-chatList`)

      data[id].avatar = res.data.avatar
      data[id].nickname = res.data.nickname
      data[id].notCount = 0
      await localforage.setItem(`${account}-chatList`, data)

      PubSub.publish('refreshChatUserList')
    }, 1000)
  }

  return (
    <div className={styles.chattingBox}>
      <ChattingHistory
        setRef={(ref) => (chatMessagesRef.current = ref)}
        chatRecordList={chatRecordList}
        userInfo={userInfo}
        chatUserId={chatUserId}
      />

      {/* 移动分割线 */}
      <div
        className="divider"
        ref={dividerRef}
        draggable="true"
        style={{
          cursor: 'ns-resize',
          height: '4px',
          background: '#d0d0d0de',
        }}
      ></div>

      <ChattingEditor
        setRef={(ref) => (messageEditorRef.current = ref)}
        chatUserId={chatUserId}
      />
    </div>
  )
}

//
// 聊天记录
function ChattingHistory({
  setRef,
  chatRecordList,
  userInfo,
  chatUserId,
}: {
  setRef: Function
  chatRecordList: chatRecordItf[]
  userInfo: getFriendInfoItf
  chatUserId: string
}) {
  const historyRef = useRef(null)

  useEffect(() => {
    setRef(historyRef.current)
  }, [setRef, chatUserId])

  // 刚开始进入到此用户的聊天框
  useEffect(() => {
    if (chatUserId) setChatHistoryList([])
  }, [chatUserId])

  //
  // 聊天记录列表
  const [chatHistoryList, setChatHistoryList] = useState<chatRecordItf[]>([])
  const [timer, setTimer] = useState<number>(null)

  useEffect(() => {
    if (!chatRecordList || chatRecordList.length === 0) return
    setChatHistoryList([...chatHistoryList, ...chatRecordList])
  }, [chatRecordList])

  useEffect(() => {
    clearTimeout(timer)
    const t = setTimeout(async () => {
      const { account } = getGlobalState().userInfo
      const data: { [key: string]: localChatUsersItf } =
        await localforage.getItem(`${account}-chatList`)
      data[chatUserId].notCount = 0
      await localforage.setItem(`${account}-chatList`, data)

      PubSub.publish('refreshChatUserList')
      PubSub.publish('addRecordFinishHandler')
    }, 1000)
    setTimer(t)
  }, [chatHistoryList])

  //
  // 聊天框用户信息
  const [nickname, setNickname] = useState<string>('')
  const [avatar, setAvatar] = useState<string>('')

  useEffect(() => {
    if (!userInfo) return
    const { id, nickname, avatar, description } = userInfo
    setAvatar(avatar)
    setNickname(nickname)
  }, [userInfo])

  return (
    <div className={styles.chattingHistory} ref={historyRef}>
      <div className={styles.nickname}>{nickname}</div>

      <div className={styles.history}>
        {chatHistoryList.map((item) => {
          return (
            <MessageItem
              key={item.id}
              record={item}
              avatar={avatar}
              nickname={nickname}
            />
          )
        })}
      </div>
    </div>
  )
}

//
// 消息详情展示卡片
function MessageItem({
  record,
  avatar,
  nickname,
}: {
  record: chatRecordItf
  avatar: string
  nickname: string
}) {
  const {
    id,
    avatar: selfAvatar,
    nickname: selfNickname,
  } = getGlobalState().userInfo
  const { masterId, receiverId, message, type, createTime } = record

  const [self, setSelf] = useState(false)

  useEffect(() => {
    if (masterId === id) setSelf(true)
    else setSelf(false)
  }, [record])

  return (
    <div
      className={[styles.messageItem, self ? styles.selfMessage : ''].join(' ')}
    >
      <div className={styles.avatar}>
        <Avatar
          src={self ? sourceUrl + selfAvatar : sourceUrl + avatar}
          shape="square"
          size={40}
          icon={<UserOutlined />}
        />
      </div>

      <div className={styles.detail}>
        <div className={styles.name}>{self ? selfNickname : nickname}</div>
        <div className={styles.message}>
          <div>{message}</div>
          <div>{createTime}</div>
        </div>
      </div>
    </div>
  )
}

//
// 消息编辑器
function ChattingEditor({
  setRef,
  chatUserId,
}: {
  setRef: Function
  chatUserId: string
}) {
  const editorRef = useRef(null)
  useEffect(() => {
    setRef(editorRef.current)
  }, [setRef])

  // 聊天消息
  const [msg, setMsg] = useState<string>('')

  // 发送消息
  const sseSendChattingMessage = async (receiverId: string, msg: string) => {
    setMsg('')
    const res = await sseSendChattingMessageApi(receiverId, msg)
    if (res.code !== 200) return message.error('发送消息错误！')
  }

  return (
    <div className={styles.chattingEditor} ref={editorRef}>
      <div className={styles.funcBar}>
        <div className={styles.funcBtn}>
          <div>图片</div>
          <div>文件</div>
          <div>视频</div>
        </div>
        <div className={styles.submitBtn}>
          <button onClick={() => sseSendChattingMessage(chatUserId, msg)}>
            发送
          </button>
        </div>
      </div>

      {/* 消息输入框 */}
      <div className={styles.messageInput}>
        <TextArea
          placeholder="消息输入框"
          value={msg}
          bordered={true}
          onChange={(event) => setMsg(event.target.value)}
          style={{ height: '100%' }}
        />
      </div>
    </div>
  )
}
